using Services;
using Services.Event;
using Services.ObjectPools;
using UnityEngine;

namespace Gobang
{
    public class PredictionDrawer : MonoBehaviour
    {
        private PredictionManager manager;
        private IObjectManager objectManager;
        private GameManager gameManager;
        private ChessboardMono chessboard;
        private IEventSystem eventSystem;

        private void Clear()
        {
            ObjectPoolUtility.RecycleMyObjects(gameObject);
        }

        private void Repaint()
        {
            if (gameManager.gameMode != EGameMode.WinRate)
                return;

            Clear();
            foreach (PredictionPointData data in manager.predictions)
            {
                IMyObject obj = objectManager.Activate("PredictionPoint", chessboard.ChessboardToWorld(data.Position), Vector3.zero, transform);
                obj.Transform.GetComponent<PredictionPoint>().Initialize(data);
            }
        }

        private void AfterGameStateChange(bool _)
        {
            Clear();
        }

        private void AfterChessChange()
        {
            Clear();
        }

        private void Awake()
        {
            eventSystem = ServiceLocator.Get<IEventSystem>();
            gameManager = ServiceLocator.Get<GameManager>();
            manager = PredictionManager.FindInstance();
            objectManager = ServiceLocator.Get<IObjectManager>();
            chessboard = ChessboardMono.FindInstance();
            manager.AfterPredictionChange += Repaint;
        }

        private void OnEnable()
        {
            eventSystem.AddListener<bool>(EEvent.AfterGameStateChange, AfterGameStateChange);
            chessboard.AfterChessChange += AfterChessChange;
        }

        private void OnDisable()
        {
            eventSystem.RemoveListener<bool>(EEvent.AfterGameStateChange, AfterGameStateChange);
            chessboard.AfterChessChange -= AfterChessChange;
        }
    }
}